<template>
  <PageWrapper 
  title="角色权限"
  >
    <BasicTable 
    :loading="loading"
    :columns="roleColumns"
    :dataSource="tableData"
    :actionColumn="{
      width: 120,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    }"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddRole">新增</a-button>
      </template>
      <template #action="{ record }">
        <TableAction 
        :actions="[
          {
            label: '编辑',
            onClick: onTableRowEdit.bind(null, record)
          },
          {
            label: '删除',
            color: 'error',
            onClick: onTableRowDel.bind(null, record)
          }
        ]"
        />
      </template>
    </BasicTable>

    <AddRoleModal @register="register" @onConfirm="onAddRoleModalConfirm" />
  </PageWrapper>
</template>

<script lang="ts" setup >
import { PageWrapper } from '@/components/Page'
import { useModal } from '@/components/Modal'
import * as api from '@/api/permisson/role'
import { BasicTable, TableAction } from '@/components/Table'
import { roleColumns } from './data'
import { formatToDateTime } from '@/utils/dateUtil';
import AddRoleModal from './components/Add-role-modal.vue'
import { IEditRoleItem } from '@/api/permisson/model';
import { IRoleItem } from '@/api/permisson/model/role';

import { useRequest } from '@vben/hooks';
import { useMessage } from '@/hooks/web/useMessage'
import { usePermission } from '@/hooks/web/usePermission';

const { hasPermission } = usePermission();
const { createMessage, createConfirm } = useMessage()
const [register, { openModal, closeModal }] = useModal();
const { loading, data: tableData, refresh } = useRequest(getRoleList)

async function getRoleList() {
  const data = await api.getRoleList()
  if (data) {
    return data.map(item => {
      return {
        ...item,
        createDate: item.createDate && formatToDateTime(item.createDate),
        updateDate: item.updateDate && formatToDateTime(item.updateDate)
      }
    })
  }
  return []
}

function onAddRole() {
  openModal(true, { isEdit: false});
}

async function onTableRowEdit(e: IRoleItem) {
  openModal(true, {...e, isEdit: true});
}

/** 删除角色 */
async function onTableRowDel(e: IRoleItem) {
  createConfirm({
    title: '提示',
    content: '是否删除角色？',
    iconType: 'warning',
    onOk: async () => {
      await api.delRole(e.id);
      createMessage.success('删除成功！');
      refresh();
    }
  });
}

async function onAddRoleModalConfirm(e: IEditRoleItem) {
  await api.addRole(e);
  closeModal();
  createMessage.success('操作成功');
  refresh();
}

</script>

<style lang="less" scoped>

</style>